<template>
	<view>
		<view class="fui-wrap fixed top right bottom left " style="z-index: 9999;" v-if="isShowTailor">
			<jp-cropper-watermark mode="free" :width="width" :height="height" :maxWidth="1024" :maxHeight="1024"
				:url="TailorSrc" @cancel="isShowTailor = false" @ok="onSubmitTailor"></jp-cropper-watermark>
		</view>

		<fui-form ref="form">
			<fui-form-item label="主页背景图" labelSize="26">
				<fui-upload :url="imageUpfileUrl" :fileList="bgPics" ref="bgPicUpload" sizeType="compressed" max="1" width="500" height="300"
					@success="bgPicUpSuccess" @error="bgPicUpError" @complete="bgPicUpComplete" Right></fui-upload>
			</fui-form-item>
			<fui-form-item label="头像" labelSize="26">
				<fui-upload :url="imageUpfileUrl" :fileList="headList" ref="HeadPicUpload" sizeType="compressed" max="1"
					@success="HeadPicUpSuccess" @error="error" @complete="HeadPicUpComplete" Right></fui-upload>
			</fui-form-item>

			<fui-form-item label="昵称" labelSize="26">
				<fui-input :borderBottom="false" :padding="[0]" placeholder="请输入您的昵称" textRight
					v-model="formData.nickName"></fui-input>
			</fui-form-item>

			<fui-form-item label="身份" labelSize="26" arrow highlight arrowColor="#d6d6d6" @click="setUserRole">
				<view style="text-align: right;">
					<text v-for="(item,index) in userRoles" :key="index">
						{{ item.LabelName }}
						<text v-if="index < userRoles.length-1"> / </text>
					</text>
				</view>
			</fui-form-item>

			<fui-form-item label="性别" highlight arrow arrowColor="#d6d6d6" labelSize="26" @click="showSex">
				<view style="float:right">{{formData.sex['text']}}</view>
			</fui-form-item>

			<fui-form-item label="生日" highlight arrow arrowColor="#d6d6d6" labelSize="26" @click="showBirthday">
				<view style="float:right">{{formData.birthday}}</view>
			</fui-form-item>

			<fui-form-item label="地区" highlight arrow arrowColor="#d6d6d6" labelSize="26" @click="showCity">
				<view style="float:right">{{formData.city}}</view>
			</fui-form-item>

			<view>
				<view class="padding-all-20">自我简介</view>
				<view class="row" style="background-color: rgba(255,255,0,0.3);padding: 8px 20px;">
					<uni-icons type="notification" size="20" color="#000"></uni-icons>
					<view class="fs-24 marginLeft-15" style="color: #000;">
						请勿带有联系方式哦,否则审核不通过
					</view>
				</view>
				<fui-textarea size="26" v-model="formData.content" placeholder="请输入内容"></fui-textarea>
			</view>
		</fui-form>
		<view class="saveBtns">
			<view style="width: 90vw; display: inline-block;">
				<fui-button background="#FFDD00" width="100%" height="70rpx" color="#000" class="saveBtn"
					@click="saveMyInfo">保存</fui-button>
			</view>
		</view>

		<view style="height:150rpx"></view>
		<fui-picker linkage :options="sexs" :show="sexShow" @change="changeSex" @cancel="cancel('sex')"></fui-picker>
		<fui-date-picker :show="birthdayShow" type="3" minDate="1940-01-01" value="1990-01-01" @change="changeBirthday"
			@cancel="cancel('birthday')"></fui-date-picker>
		<fui-picker linkage :layer="3" :options="cityOptions" :show="cityShow" @change="changeCity"
			@cancel="cancel('city')"></fui-picker>
	</view>
</template>

<script>
	import cityData from "@/script/city.js";
	//校验规则
	const rules = [];
	export default {
		data() {
			return {
				width: 600,
				height: 400,
				// 裁剪框是否显示
				isShowTailor: false,
				// 接收裁剪的图片
				TailorSrc: '',

				userInfo: {},
				imageUpfileUrl: 'https://api.meimo.comdns.cn/common/Upload/upload?file=userbase&type=image',
				bgPics: [],
				bgpic: '',
				headList: [],
				headpic: '',
				//上传视频接口地址
				videoUpLoadUrl: 'https://api.meimo.comdns.cn/common/Upload/upload?file=uservideo&type=video',
				//上传状态，用于保存或其他操作时做判断
				upStatus: '',
				//上传的视频地址列表
				VideoUrls: [],
				//表单data数据
				formData: {
					saveType: 0,
					bgPic: '',
					headPic: '',
					nickName: '',
					sex: {
						value: -1,
						text: '请设置性别'
					},
					birthday: '请设置您的生日',
					city: '请设置您所在的地区',
					cityJson: {},
					cityCode: [],
					content: '',
					video: ''
				},
				sexShow: false,
				sexs: [{
						value: -1,
						text: '请设置性别'
					},
					{
						value: 0,
						text: '女'
					},
					{
						value: 1,
						text: '男'
					}
				],
				birthdayShow: false,
				cityShow: false,
				cityOptions: [],
				userRoles: [{
					LabelID: 0,
					LabelName: '请设置您的身份角色'
				}],
				// 判断裁切类型，0 背景裁切、1 头像裁切
				CuttingType: 0,
				// 是否裁剪
				isCropping: false,
			};
		},
		onLoad(options) {
			this.cityOptions = cityData.cityData;
			this.getUserInfo();
			uni.$on('resultData', (params) => {
				if (!!params) this.userRoles = params;
			})

		},
		onShow() {},
		onUnload() {
			uni.removeStorageSync("bgPics")
			uni.removeStorageSync("headList")
		},
		methods: {
			onCancel() {
				this.isShowTailor = false
			},
			// 上传
			uploadImage(tmpFile) {
				return new Promise((reslove, reject) => {
					uni.uploadFile({
						url: this.imageUpfileUrl,
						filePath: tmpFile,
						name: "file",
						formData: {},
						success: (uploadFileRes) => {
							reslove(this.$baseUrl + JSON.parse(uploadFileRes.data).fileName)
						}
					})
				})
			},

			// 旋转裁切
			onRotateTailor() {
				this.$refs.tailor && this.$refs.tailor.rotate()
			},
			// 确定裁切
			async onSubmitTailor(fileImage) {
				// console.log('file', fileImage)

				if (this.isCropping) {
					this.isCropping = false;

					if (this.CuttingType === 0) {
						this.width = 600;
						this.height = 400;
						this.bgPics = [];
						let localStorageBgPics = await this.uploadImage(fileImage.path);
						uni.setStorageSync("bgPics", localStorageBgPics);
						this.bgPics.push(localStorageBgPics);
						// console.log('getStorageSync', uni.getStorageSync("bgPics"));
						if (!!localStorageBgPics) uni.hideLoading();

					} else {
						this.width = 400;
						this.height = 400;
						this.headList = [];
						let localStorageheadList = await this.uploadImage(fileImage.path);
						uni.setStorageSync("headList", localStorageheadList);
						this.headList.push(localStorageheadList);
						// console.log('getStorageSync', uni.getStorageSync("headList"));
						if (!!localStorageheadList) uni.hideLoading();
					}
				}

				// 关闭裁切
				this.isShowTailor = false
			},
			getUserInfo() {
				this.bgPics = []
				this.headList = []
				this.$httpost('/UserAction/getUserInfo').then(res => {
					// console.log(res)
					if (res.code == 200) {
						this.userInfo = res.data.UserInfo
						if (res.data.UserRole.length > 0) {
							this.userRoles = res.data.UserRole
						}

						if (uni.getStorageSync("bgPics")) {
							this.bgPics.push(uni.getStorageSync("bgPics"))
						} else {
							if (this.userInfo.BackgroundPic) {
								this.bgPics[0] = this.userInfo.BackgroundPic
								// // console.log(this.bgPics[0])
							}
						}

						if (uni.getStorageSync("headList")) {
							this.headList.push(uni.getStorageSync("headList"))
						} else {
							if (this.userInfo.WxHeadPic) {
								this.headList[0] = this.userInfo.WxHeadPic
							}
						}
						this.formData.nickName = this.userInfo.NickName

						if (!this.userInfo.UserSex) {
							this.formData.sex = this.formData.sex
						} else {
							this.formData.sex = JSON.parse(this.userInfo.UserSex)
						}
						if (!this.userInfo.UserBirth) {
							this.formData.birthday = '请设置您的生日'
						} else {
							this.formData.birthday = this.userInfo.UserBirth
						}
						if (!this.userInfo.UserCity) {
							this.formData.city = '请设置您所在的城市'
						} else {
							this.formData.cityJson = JSON.parse(this.userInfo.UserCityJson)
							this.formData.city = this.userInfo.UserCity
						}

						this.formData.content = this.userInfo.UserMemo

					}

				})
			},



			bgPicUpSuccess(e) {
				// console.log(e,'成功')
				let res = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}")
				this.upStatus = e.status
				if (res.fileName) {
					//处理结果返回给组件 
					//res.data.url为上传成功后返回的图片地址
					//e.index为图片索引值
					this.$refs.bgPicUpload.result(this.$baseUrl + res.fileName, e.index)
					// console.log(this.$baseUrl + res.fileName)
				}
			},
			//上传失败时触发
			bgPicUpError(e) {
				// console.log(e)
				this.upStatus = e.status
			},
			//选择视频或上传完成时触发
			bgPicUpComplete(e) {
				// console.log('准备裁切！', e)
				// 上传触发
				if (e.action == 'choose') {
					// console.log('上传背景成功',e)
					this.TailorSrc = ''
					this.upStatus = e.status
					this.TailorSrc = e.urls[0]
					this.CuttingType = 0
					this.width = 600;
					this.height = 400;
					this.isCropping = true;
					// this.bgPics = e.urls
					// // 打开裁切
					if (this.TailorSrc != '') this.isShowTailor = true;
				}

				// 删除触发
				if (e.action == 'delete') {
					// 表示已经删除图片
					this.bgPics = []
				}


				if (this.upStatus === 'success' && e.action === 'upload') {
					// // console.log('this.bgPics', this.bgPics)
				}
			},
			HeadPicUpSuccess(e) {
				// console.log(e)
				let res = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}")
				this.upStatus = e.status
				if (res.fileName) {
					//处理结果返回给组件 
					//res.data.url为上传成功后返回的图片地址
					//e.index为图片索引值
					this.$refs.HeadPicUpload.result(this.$baseUrl + res.fileName, e.index)
				}
			},
			//上传失败时触发
			HeadPicUpError(e) {
				// console.log(e)
				this.upStatus = e.status
			},
			//选择视频或上传完成时触发
			HeadPicUpComplete(e) {
				if (e.action == 'choose') {
					// console.log('上传头像成功',e)
					this.TailorSrc = '';
					this.upStatus = e.status;
					this.TailorSrc = e.urls[0];
					this.CuttingType = 1;
					this.width = 400;
					this.height = 400;
					this.isCropping = true;

					// // 打开裁切
					if (this.TailorSrc != '') this.isShowTailor = true;
				}

				// 删除触发
				if (e.action == 'delete') {
					// 表示已经删除图片
					this.headList = [];
				}
				// this.headList = e.urls
				// if (this.upStatus === 'success' && e.action === 'upload') {
				// console.log(this.headList)
				// }
			},
			//上传成功时触发
			VideoUpSuccess(e) {
				let res = JSON.parse(e.res.data.replace(/\ufeff/g, "") || "{}")
				this.upStatus = e.status
				if (res.fileName) {
					//处理结果返回给组件 
					//res.data.url为上传成功后返回的视频地址
					//e.index为视频索引值
					this.$refs.VideoUpload.result(this.$baseUrl + res.fileName, e.index)
				}
			},
			//上传失败时触发
			VideoUpError(e) {
				this.upStatus = e.status
			},
			//选择视频或上传完成时触发
			VideoUpComplete(e) {
				this.upStatus = e.status
				this.VideoUrls = e.urls
				if (this.upStatus === 'success' && e.action === 'upload') {
					// console.log(this.VideoUrls)
				}
			},
			showSex() {
				this.sexShow = true
			},
			showBirthday() {
				this.birthdayShow = true
			},
			showCity() {
				this.cityShow = true
			},
			changeSex(e) {
				// console.log(e)
				this.formData.sex = e
				this.sexShow = false
			},
			changeBirthday(e) {
				// console.log(e)
				this.formData.birthday = e.result
				this.birthdayShow = false
			},
			changeCity(e) {
				// console.log(e)
				this.formData.cityJson = e
				this.formData.city = e.result
				this.formData.cityCode = e.value
				this.cityShow = false
			},
			cancel(type) {
				if (type == 'sex') {
					this.sexShow = false
				}
				if (type == 'birthday') {
					this.birthdayShow = false
				}
				if (type == 'city') {
					this.cityShow = false
				}
			},
			goPage(url) {
				uni.navigateTo({
					url: url
				})
			},
			setUserRole() {
				// console.log('setUserRole')
				// this.goPage('/myPages/pages/setUerRole');				
				this.$common.goNavPage('/myPages/pages/setUerRole');
			},
			saveMyInfo() {
				// console.log('form', this.formData);
				try {
					if (this.bgPics.length == 0) {
						this.$common.showToast("请上传背景图！");
						return false;
					}
					if (this.headList.length == 0) {
						this.$common.showToast("请上传头像！");
						return false;
					}
					if (this.formData.nickName == '') {
						this.$common.showToast("请为自己起个昵称！");
						return false;
					}
					if (/.{10,}/.test(this.formData.nickName)) {
						this.$common.showToast("请输入10位以内昵称！");
					}

					if (this.userRoles.length === 0) {
						this.$common.showToast("请设置您的身份角色！");
						return false;
					} else {
						if (this.userRoles[0].LabelID === 0) {
							this.$common.showToast("请设置您的身份角色！");
							return false;
						}
					}

					if (this.formData.sex.value == -1) {
						this.$common.showToast("请设置您的性别！");
						return false;
					}
					if (this.formData.birthday == '请设置您的生日') {
						this.$common.showToast("请设置您的生日！");
						return false;
					}

					if (this.formData.city == '请设置您所在的地区') {
						this.$common.showToast("请设置您所在的地区！");
						return false;
					}
					const nickNamelength = this.formData.nickName.replace(/[\u4e00-\u9fa5]/g, 'aa').length
					if (nickNamelength > 12) {
						uni.showToast({
							title: '昵称不能超过12个字符（中文6个字）',
							icon: 'none'
						})
						return false;
					}

					this.formData.bgPic = this.bgPics.length !== 0 ? this.bgPics[0] :
						'https://img.1ppt.com/uploads/allimg/1902/1_190213153422_2.JPG';
					this.formData.headPic = this.headList[0]
					this.formData.video = this.VideoUrls[0]

					this.$httpost('/UserAction/saveUserInfo', this.formData).then(res => {
						if (res.code == 200) {
							uni.removeStorageSync("bgPics")
							uni.removeStorageSync("headList")
							// console.log(res)
							// this.$common.goNavPage("/myPages/pages/mypage");

							// console.log("/myPages/pages/mypage");
							uni.showToast({
								title: "保存成功！",
								icon: "success"
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 200)
						}
					});
				} catch (err) {
					// console.log(err)
				}
			}
		}
	}
</script>

<style lang="scss">
	.saveBtns {
		// width:100vw;
		position: fixed;
		z-index: 100;
		bottom: 20rpx;
		left: 0%;
		right: 0%;
		text-align: center;
	}

	.saveBtn {
		margin: auto;
	}


	.fui-cropper__tabbar {
		/* #ifndef APP-NVUE */
		display: flex;
		z-index: 20;
		position: relative;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		height: 120rpx;
		left: 0;
		right: 0;
		bottom: 0;
		/* #ifdef APP-NVUE */
		border-top: 0.5px solid #666;
		/* #endif */
	}

	/* #ifndef APP-NVUE */
	.fui-cropper__tabbar::before {
		content: ' ';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 1px;
		border-top: 1px solid #666;
		transform: scaleY(0.5);
		transform-origin: 0 0;
		z-index: 21;
	}

	/* #endif */

	.fui-text {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		font-size: 32rpx;
		font-weight: normal;
		color: #fff;
		flex: 1;
		text-align: center;
		justify-content: center;
		align-items: center;
		height: 80rpx;
		line-height: 80rpx;
		/* #ifdef H5 */
		cursor: pointer;
		/* #endif */
	}
</style>